<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="nameSearch"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :highlight-current="true"
          :expand-on-click-node="false"
          default-expand-all
          :data="depts"
          :props="defaultProps"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'addEmployee'" size="mini" type="primary" @click="$router.push(`/employee/detail`)">添加员工</el-button>
          <el-button size="mini" @click="importEmployee">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          :header-cell-style="{background:'#f5f6f8',color:'#909399'}"
        >
          <el-table-column width="100" prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.slice(0,1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" align="center" label="姓名" />
          <el-table-column sortable prop="mobile" align="center" label="手机号" />
          <el-table-column sortable prop="workNumber" align="center" label="工号" />
          <el-table-column prop="workNumber" align="center" label="聘用形式">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" align="center" label="部门" />
          <el-table-column sortable prop="timeOfEntry" align="center" label="入职时间" />
          <el-table-column width="200" align="center" label="操作">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="selectRole(row)">角色</el-button>
              <el-popconfirm
                title="确定删除该员工吗？"
                style="margin-left: 10px;"
                @onConfirm="handleDel(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :page-size="10"
          :pager-count="7"
          layout="->,total, prev, pager, next"
          :total="total"
          :current-page="queryParams.page"
          style="padding: 20px 0"
          @current-change="pageChange"
          @prev-click="pagePrev"
          @next-click="pageNext"
        />
      </div>
    </div>
    <ImportExcel ref="importExcel" @dataUpload="getUserList" />
    <SelectRole ref="selectRole" />
  </div>
</template>

<script>
import { getDeptsList } from '@/api/department'
import { getUserList, delUser, exportUser } from '@/api/employee'
import { transListToTree } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './component/ImportExcel.vue'
import SelectRole from './component/SelectRole.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel,
    SelectRole
  },
  data() {
    return {
      depts: [],
      // 使depts数据映射到组件
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading: false,
      showDialog: false,
      tableData: [],
      total: 0,
      queryParams: {
        keyword: '',
        page: 1,
        pagesize: 10,
        departmentId: ''
      }
    }
  },
  created() {
    this.getDeptsList()
  },
  methods: {
    // 获取树组件数据
    async getDeptsList() {
      const res = await getDeptsList()
      this.depts = transListToTree(res, 0)
      // 获取首个部门ID方便后续查询信息,
      this.queryParams.departmentId = this.depts[0].id
      // 设置当前默认选中的项为第一项.等到页面加载完后才能赋值
      this.$nextTick(() => {
        this.$refs.deptTree?.setCurrentKey(this.queryParams.departmentId)
      })
      await this.getUserList()
    },
    // 选择节点
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getUserList()
    },
    // 名字搜索
    nameSearch() {
      // 防抖优化,没执行完上一个定时器,就再开一个新的
      // 避免频繁请求
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getUserList()
      }, 500)
    },
    // 获取员工信息
    async getUserList() {
      this.loading = true
      const res = await getUserList(this.queryParams)
      this.tableData = res.rows
      this.total = res.total
      this.loading = false
    },
    // 分配角色
    selectRole(row) {
      this.$refs.selectRole.open(row)
    },
    // 删除员工
    async handleDel(id) {
      await delUser(id)
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.pagePrev()
      } else {
        await this.getUserList()
      }
      this.$message.success('删除员工成功')
    },
    // 导出员工表
    async exportEmployee() {
      const res = await exportUser()
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    importEmployee() {
      this.$refs.importExcel.open()
    },
    // 页面跳转
    pageChange(page) {
      this.queryParams.page = page
      this.getUserList()
    },
    // 页面跳转
    pagePrev() {
      this.queryParams.page--
      this.getUserList()
    },
    // 页面跳转
    pageNext() {
      this.queryParams.page++
      this.getUserList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
.upload{
  width: 360px;
  height: 180px;
  margin: 0 auto;
  border: 1px #c0c4cc dashed;
}

</style>
